<template>
	<view>
		<u-sticky>
			<!-- 吸顶进度条,只能有一个根元素 -->
			<u-search placeholder="请输入关键字" shape="square" @clear="eventClear" @search="eventSearch"
				:show-action="false" v-model="keyword">
			</u-search>
		</u-sticky>
		<view v-for="item of resources" :key="item.id" @click="eventGoDetailPage(item)">
			<view>
				<u-icon name="checkmark-circle-fill" color="#55aa00" size="28"></u-icon>
				{{item.title}}
			</view>
			<u-image :src="item.base64img" mode="widthFix">
				<u-loading color="#2979ff" slot="loading">
				</u-loading>
			</u-image>
		</view>
		<u-loadmore :status="status" :icon-type="iconType" :load-text="loadText" />
	</view>
</template>

<script>
	import parser from './htmlparser/index.js'
	import resourceService from './downloader/db.js'
	import downloader from './downloader/index.js'
	export default {
		data() {
			return {
				keyword: '',
				status: 'loadmore',
				iconType: 'flower',
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				resources: [],
				hasNext: true,
				page: {
					pageIndex: 1,
					pageSize: 10
				}
			}
		},
		onReachBottom() {
			if (this.hasNext) {
				this.loadData();
			}
		},
		onLoad() {
			this._onLoad();
		},
		mounted() {},
		methods: {
			onImgLoad(e) {
				console.log(e)
			},
			onImgError(e) {
				console.log(e)
			},
			eventGoDetailPage(item) {
				var navData = JSON.stringify(item); // 这里转换成 字符串
				uni.navigateTo({
					url: './detail?index=' + navData
				})
			},

			async _onLoad() {
				await resourceService.open();
				this.loadData();
			},
			eventClear() {
				this.eventSearch("");
			},
			eventSearch(keyword) {
				this.keyword = keyword;
				this.page.pageIndex = 1;
				this.resources = [];
				this.hasNext = true;
				this.loadData();
			},

			async loadData(url) {
				if (!this.hasNext) {
					return;
				}
				this.status = 'loading';
				console.log('请求数据')
				resourceService.page(this.keyword, this.page.pageIndex, this.page.pageSize).then(res => {
					this.hasNext = res.data.next
					if (this.hasNext) {
						this.status = 'loadmore';
						this.page.pageIndex++;
					} else {
						this.status = 'nomore'
					}
					res.data.data.forEach(item => {
						item.base64img = ''
					})
					this.resources = this.resources.concat(res.data.data)
					res.data.data.forEach(item => {
						this.getLocalImg(item)
					})

				})
			},
			getLocalImg(item) {
				downloader.getFileBase64(plus.io.convertLocalFileSystemURL(item.img)).then(str => {
					item.base64img = str
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-demo {}
</style>
